<?php

namespace app\admin\controller;

use app\admin\model\Identity;
use app\admin\model\PostCate;
use app\admin\model\Resource;
use app\admin\model\ResourceCate;
use app\admin\model\MemberLevel;
use app\admin\validate\MemberLevel as memberLevelValidate;
use app\AdminController;
use app\admin\validate\Identity as identityValidate;
use app\admin\validate\PostCate as postCateValidate;
use app\admin\validate\ResourceCate as resourceCateValidate;
use app\AliOosFile;
use think\exception\ValidateException;
use think\facade\Log;
use app\admin\model\LinksMessage;
use app\admin\validate\LinksMessage as linksMessageValidate;

/**
 * 系统设置
 * Class SystemSett
 * @package app\admin\controller
 */
class SystemSett extends AdminController
{
    /**
     * 用户身份
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['name', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = Identity::where($where)->page($page, $limit)->select();
        $count = Identity::where($where)->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }
        return view();
    }

    /**
     * 添加身份
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function identityAdd()
    {
        $info = new Identity();

        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(identityValidate::class)->scene('insert')->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;
            $info->save($data);
            $this->success('操作成功', url('/systemsett/index'));
        }

        return view('', ['info' => $info]);
    }

    /**
     * 编辑
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function identityEdit()
    {
        $id = intval($this->request->param('id'));
        if (!$id) {
            $this->error('参数错误');
        }

        $info = Identity::find($id);


        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(identityValidate::class)->scene('edit')->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;

            Identity::update($data, ['id' => $data['id']]);

            $delPathArr = [];
            // 更改了默认图标
            if ($data['default_icon'] != $info['default_icon']) {
                $delPathArr[] = $info['default_icon'];
            }
            // 更改了选中图标
            if ($data['selected_icon'] != $info['selected_icon']) {
                $delPathArr[] = $info['selected_icon'];
            }
            if ($delPathArr) {
                foreach ($delPathArr as $path) {
                    Upload::delImageOrVideo($path);
                }
            }
            $this->success('操作成功', url('/systemsett/index'));
        }

        return view('', ['info' => $info]);
    }


    /**
     * 删除身份
     */
    public function identityDel()
    {
        $id = intval($this->request->param('id'));
        $info = Identity::destroy($id);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/systemsett/index'));
    }

    /**
     * 身份状态修改
     */
    public function identityChangeStatus()
    {
        $id = input('id', 0);
        $field = input('field', '');
        $find = Identity::find($id);
        if (!empty($find)) {
            $status = $find[$field] == 0 ? 1 : 0;
            Identity::where(['id' => $id])->update([$field => $status]);
        }
        echo json_encode(1);
        exit;
    }

    /**
     * 社群分类
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cate()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['name', 'like', '%' . $keywords . '%'];
        }

//        $page = input('page',1);
//        $limit = input('limit',10);
        $list = ResourceCate::where($where)->select();
        $list = $list ? $list->toArray() : [];

        $arr = [];
        foreach ($list as $k => &$v) {
            if ($v['pid'] != 0) {
                $v['cate_count'] = Resource::where('FIND_IN_SET('.$v['id'].',cids)')->count();
                $arr[$v['pid']][] = $v['cate_count'];
            }
        }

        foreach ($list as $k => $v) {
            if ($v['pid'] == 0) {
                $sum = array_sum($arr[$v['id']]);
                $list[$k]['cate_count'] = $sum;
            }
        }

        $count = ResourceCate::where($where)->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }
        return view();
    }

    /**
     * 添加子栏目
     * @return \think\response\Json
     */
    public function addSubCate()
    {
        $param = $this->request->param();
        if (!$this->request->isPost()) {
            return json(['code' => 0, 'msg' => '请求错误']);
        }
        if (!isset($param['pid'])) {
            return json(['code' => 0, 'msg' => '参数错误']);
        }
        try {
            validate(resourceCateValidate::class)->scene('insert')->check($param);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }
        $resourceCateModel = new ResourceCate();
        $resourceCateModel->save($param);
        $this->success('操作成功', url('/systemsett/cate'));
    }

    /**
     * 添加社群顶级分类
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cateAdd()
    {
        $resourceLabelModel = new ResourceCate();

        if (request()->isPost()) {
            $info = request()->post();
            try {
                validate(resourceCateValidate::class)->scene('insert')->check($info);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }
            $info['pid'] = 0;

            $resourceLabelModel->save($info);
            $this->success('操作成功', url('/systemsett/cate'));
        }
    }

    /**
     * 编辑社群分类
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function cateEdit()
    {
        if (request()->isPost()) {
            $resourceLabelModel = new ResourceCate();
            $param = $this->request->param();
            // 编辑
            if (empty($param['id'])) {
                $this->error('参数错误');
            }
            try {
                validate(resourceCateValidate::class)->scene('edit')->check($param);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }
            $resourceLabelModel->where(['id' => $param['id']])->save(['name' => $param['name']]);
            $this->success('操作成功', url('/systemsett/cate'));
        }
    }

    /**
     * 删除社群分类
     */
    public function cateDel()
    {
        $param = $this->request->param();
        if (!isset($param['id']) || !isset($param['pid'])) {
            $this->error('参数错误');
        }
        $where = ['id' => $param['id'], 'pid' => $param['pid']];
        $find = ResourceCate::where($where)->find();
        if (empty($find)) {
            $this->error('未找到数据');
        }
//        var_dump($param);
        // 二级分类，拿到当前id查询是否已存在社群
        if ($param['pid'] > 0) {
            $column = Resource::whereFindInSet('level2', $param['id'])->column('id');

            $join = join('、', $column);

            if ($column) {
                return json(['code' => 0, 'msg' => '该分类已存在《社群列表 <span style="color:red">' . $join . '</span> 》，无法删除']);
            }
            // 顶级分类，查询是否还存在二级分类
        } else {
            $all = ResourceCate::where('pid', $param['id'])->select();
            $all = $all ? $all->toArray() : [];
            if (!empty($all)) {
                return json(['code' => 0, 'msg' => '该分类下还存在子分类，无法删除']);
            }
        }

        // 执行删除
        $info = ResourceCate::destroy($param['id']);
        if (!($info)) $this->error('操作失败');

        $this->success('操作成功', url('/systemsett/cate'));
    }

    /**
     * 会员级别
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function memberLevel()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['level|price|validity', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = MemberLevel::where($where)->page($page, $limit)->select();
        $count = MemberLevel::where($where)->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }
        return view();
    }

    /**
     * 添加会员级别
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function memberLevelAdd()
    {
        $info = new MemberLevel();

        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(memberLevelValidate::class)->scene('insert')->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;
            $info->save($data);

            // 存储图片/视频到阿里云
            $AliOos = new AliOosFile();
            // 去除开头的 /
            $urls = substr($data['images'], 1);
            $AliOos->upload($_SERVER['DOCUMENT_ROOT'] . $data['images'], $urls);

            $this->success('操作成功', url('/systemsett/memberLevel'));
        }

        return view();
    }

    /**
     * 编辑会员级别
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function memberLevelEdit()
    {
        $memberLevelModel = new MemberLevel();
        $id = intval($this->request->param('id'));
        $info = $memberLevelModel->find($id);

        $yImages = $info['images'];

        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(memberLevelValidate::class)->scene('edit')->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;
            $info->save($data);

            $AliOos = new AliOosFile();
            // 去除开头的 /
            $urls = substr($data['images'], 1);
            $AliOos->upload($_SERVER['DOCUMENT_ROOT'] . $data['images'], $urls);

            $this->success('操作成功', url('/systemsett/memberLevel'));
        }

        $info['yimages'] = config('url.url') . $info['images'];

        return view('', ['info' => $info]);
    }

    /**
     * 删除会员级别
     */
    public function memberLevelDel()
    {
        $id = intval($this->request->param('id'));
        $info = MemberLevel::destroy($id);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/systemsett/memberLevel'));
    }

    /**
     * 会员级别状态修改
     */
    public function memberLevelChangeStatus()
    {
        $id = input('id', 0);
        $field = input('field', '');
        $find = MemberLevel::find($id);
        if (!empty($find)) {
            $status = $find[$field] == 0 ? 1 : 0;
            IdentMemberLevelity::where(['id' => $id])->update([$field => $status]);
        }
        echo json_encode(1);
        exit;
    }

    public function postCate()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['name', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = PostCate::where($where)->page($page, $limit)->select();
        $count = PostCate::where($where)->count();
        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }
        return view();
    }

    /**
     * 编辑/添加帖子分类
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function postCateEdit()
    {
        $postCateModel = new PostCate();
        $id = $this->request->param('id') ? intval($this->request->param('id')) : '';

        // 默认为 "添加" 操作
        $scene = 'insert';
        $info = $postCateModel;
        // 编辑
        if (!empty($id)) {
            $scene = 'edit';
            $info = $postCateModel->find($id);
        }

        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(postCateValidate::class)->scene($scene)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;
            $info->save($data);
            $this->success('操作成功', url('/systemsett/postcate'));
        }

        return view('', ['info' => $info]);
    }

    /**
     * 删除帖子分类
     */
    public function postCateDel()
    {
        $id = intval($this->request->param('id'));
        $info = PostCate::destroy($id);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/systemsett/postcate'));
    }

    /**
     * 帖子分类状态修改
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function postCateChangeStatus()
    {
        $id = input('id', 0);
        $field = input('field', '');
        $find = PostCate::find($id);
        if (!empty($find)) {
            $status = $find[$field] == 0 ? 1 : 0;
            PostCate::where(['id' => $id])->update([$field => $status]);
        }
        echo json_encode(1);
        exit;
    }


    /**
     * 云links通知
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function linksMessage()
    {
        $where = [];
        $keywords = trim(input('keywords', ''));
        if (!empty($keywords)) {
            $where[] = ['title', 'like', '%' . $keywords . '%'];
        }

        $page = input('page', 1);
        $limit = input('limit', 10);
        $list = LinksMessage::where($where)->where('status', '<>', -1)->page($page, $limit)->order('create_time','desc')->select();
        $count = LinksMessage::where($where)->count();

        if (request()->isPost()) {
            return json(['data' => ['code' => 0, 'msg' => '数据列表', 'count' => $count, 'list' => $list]]);
        }

        return view();
    }

    /**
     * 添加/编辑云links通知
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function linksMessageEdit()
    {
        $linksMessageModel = new LinksMessage();
        $id = $this->request->param('id') ? intval($this->request->param('id')) : '';

        // 默认为 "添加" 操作
        $scene = 'insert';
        $info = $linksMessageModel;
        // 编辑
        if (!empty($id)) {
            $scene = 'edit';
            $info = $linksMessageModel->find($id);
        }

        if (request()->isPost()) {
            $data = request()->post();
            try {
                validate(linksMessageValidate::class)->scene($scene)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $data['status'] = isset($data['status']) && $data['status'] == 'on' ? 1 : 0;
            $info->save($data);
            $this->success('操作成功', url('/systemsett/linksMessage'));
        }

        return view('', ['info' => $info]);
    }

    /**
     * 云links通知删除
     */
    public function linksMessageDel()
    {
        $id = intval(request()->param('id'));
        // 不做真实删除   ps：后续这里需要查询推荐表是否存在该社群数据
        $info = LinksMessage::update(['status' => -1], ['id' => $id]);
        if (!($info)) $this->error('操作失败');
        $this->success('操作成功', url('/systemsett/linksMessage'));
    }

    /**
     * 云links通知状态修改
     */
    public function linksMessageChangeStatus()
    {
        $id = input('id', 0);
        $field = input('field', '');
        $find = LinksMessage::find($id);
        if (!empty($find)) {
            $status = $find[$field] == 0 ? 1 : 0;
            LinksMessage::where(['id' => $id])->update([$field => $status]);
        }
        echo json_encode(1);
        exit;
    }

}